import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:mime_type/mime_type.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';

Future<String> imageProviderToBase64(ImageProvider imageProvider) async {
  // 获取图片的配置信息
  final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty);
  // 等待图像加载完成
  final completer = Completer<Uint8List>();
  final listener = new ImageStreamListener((ImageInfo image, bool sync) async {
    final ByteData byteData = await image.image.toByteData(format: ImageByteFormat.png);
    final Uint8List pngBytes = byteData.buffer.asUint8List();
    completer.complete(pngBytes);
  });
  stream.addListener(listener);
  final Uint8List bytes = await completer.future;
  // 将字节数组转换为base64字符串
  String base64String = base64Encode(bytes);
  return base64String;
}

Future<String> getImageBase64(String imagePath, String mediaType) async {
  final ByteData imageData = await rootBundle.load(imagePath);
  final Uint8List bytes = imageData.buffer.asUint8List();
  final String base64 = base64Encode(bytes);
  return 'data:$mediaType;base64,$base64';
}

String convertImageFile2Base64(File f) {
  String mimeType = mime(f.path);
  String data = base64Encode(f.readAsBytesSync());
  return 'data:$mimeType;base64,$data';
}
